package com.zscat.mallplus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.corba.se.spi.ior.ObjectKey;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.dms.service.IDmsOrderService;
import com.zscat.mallplus.dms.service.IMealService;
import com.zscat.mallplus.dms.service.IRoomService;
import com.zscat.mallplus.enums.DeviceStatus;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.RoomStatus;
import com.zscat.mallplus.qsg.QsgDevice;
import com.zscat.mallplus.qsg.QsgDeviceTask;
import com.zscat.mallplus.qsg.QsgMeal;
import com.zscat.mallplus.qsg.QsgRoom;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.OssUtil;
import com.zscat.mallplus.vo.TimeAxis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * 设备管理Controller
 */
@RestController
@Api(tags = "QsgDeviceController", description = "设备相关管理")
@RequestMapping("/api/dms")
public class QsgDeviceController {

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IMealService mealService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IDmsOrderService orderService;

    @IgnoreAuth
    @GetMapping(value = "/device/list")
    @ApiOperation(value = "根据店铺id查询设备列表")
    public Object getAllDevice(Long storeId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        qw.orderByAsc("sort");
        List<QsgDevice> devices = deviceService.list(qw);
        if (null != devices && devices.size() > 0) {
            for (QsgDevice device : devices) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("device_id", device.getId());
                QsgRoom room = roomService.getOne(queryWrapper);
                if (device.getOlStatus() == DeviceStatus.OFFLINE.getValue()) {//设备离线时房间离线，并记录下离线前的状态
                    if (room.getStatus() != RoomStatus.OFFLINE.getValue()) {
                        room.setBeforeStatus(room.getStatus());
                        room.setStatus(RoomStatus.OFFLINE.getValue());
                        roomService.updateById(room);
                    }
                }
                if (null != room && null != room.getBeforeStatus() && device.getOlStatus() == DeviceStatus.ONLINE.getValue()) {
                    room.setStatus(room.getBeforeStatus());
                    roomService.updateById(room);
                }
                device.setRoom(room);
                Date date = new Date();
                String now = DateUtil.dateToString(date, "yyyy/MM/dd HH:mm:ss");
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.le("start_time", now);
                queryWrapper1.ge("end_time", now);
                queryWrapper1.eq("device_id", device.getId());
                queryWrapper1.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
                queryWrapper1.orderByAsc("start_time");
                List<DmsOrder> orders = orderService.list(queryWrapper1);//当前进行的订单
                if (null != orders && orders.size() > 0) {
                    if (device.getOlStatus() == DeviceStatus.ONLINE.getValue() && null != room) {
                        //时间到了并且设备在线，直接将房间改为使用中
                        room.setStatus(RoomStatus.USRING.getValue());
                        room.setBeforeStatus(room.getStatus());
                        roomService.updateById(room);
                        device.setRoom(room);
                    }
                    String[] times = StringUtils.split(orders.get(0).getEndTime(), " ");
                    device.setEndTime(times[1]);
                    List<Integer> currentOrderArea = new ArrayList<>();
                    QsgMeal meal = mealService.getById(orders.get(0).getMealId());
                    if (null != meal && null != meal.getDuration()) {
                        for (int i = new Date(orders.get(0).getStartTime()).getHours(); i < new Date(orders.get(0).getStartTime()).getHours() + meal.getDuration(); i++) {
                            currentOrderArea.add(i);
                        }
                    }
                    device.setCurrentOrderArea(currentOrderArea);
                    QueryWrapper yyQw = new QueryWrapper();
                    yyQw.eq("start_time", orders.get(0).getEndTime());
                    yyQw.eq("device_id", device.getId());
                    yyQw.eq("member_id", orders.get(0).getMemberId());
                    yyQw.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
                    DmsOrder order = orderService.getOne(yyQw);//当前进行的订单的续费订单
                    if (null != order) {
                        times = StringUtils.split(order.getEndTime(), " ");
                        List<Integer> currentYuyueArea = new ArrayList<>();
                        for (int i = new Date(order.getStartTime()).getHours(); i < new Date(order.getStartTime()).getHours() + order.getDuration(); i++) {
                            currentYuyueArea.add(i);
                        }
                        device.setYuyueOrderArea(currentYuyueArea);
                        device.setEndTime(times[1]);
                    }
                }
                QueryWrapper yyQw = new QueryWrapper();
                yyQw = new QueryWrapper();
                yyQw.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
                yyQw.le("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd") + " 23:59:59");// 此处只取今日数据，故开始时间需要控制在今天
                yyQw.eq("device_id", device.getId());
                List<Integer> status = new ArrayList<>();
                status.add(OrderStatus.HAS_PAYMONEY.getValue());
                status.add(OrderStatus.WAIT_CANNEL.getValue());
                yyQw.in("order_status", status);
                List<DmsOrder> orders1 = orderService.list(yyQw);
                if (null != orders1 && orders1.size() > 0) {
                    List<Integer> currentYuyueArea = new ArrayList<>();
                    for (DmsOrder order : orders1) {
                            for (int i = new Date(order.getStartTime()).getHours(); i < new Date(order.getStartTime()).getHours() + order.getDuration(); i++) {
                                currentYuyueArea.add(i);
                            }
                    }
                    device.setYuyueOrderArea(currentYuyueArea);
                }
                setTimeAxis(device);
            }
        }
        collection(devices);
        return new CommonResult().success(devices);
    }

    @IgnoreAuth
    @GetMapping(value = "/device/getIdleDevice")
    @ApiOperation(value = "查询空闲的房间")
    public Object getIdleDevice(@RequestParam Long storeId,
                                @RequestParam String startTime,
                                @RequestParam String endTime) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id",storeId);
        qw.eq("is_mealdevice",0);
        List<QsgDevice> devices = deviceService.list(qw);
        for (QsgDevice device : devices){

        }
        return new CommonResult().success(devices);
    }

    @IgnoreAuth
    @GetMapping(value = "/device/changeRoom")
    @ApiOperation(value = "换房间")
    public Object changeRoom(@RequestParam String orderSn,
                                @RequestParam Long deviceId) {
        /*
            1.更换订单的房间相关信息
            3.重新发送时间
         */
        QueryWrapper qw = new QueryWrapper();
        qw.eq("order_sn",orderSn);
        DmsOrder order = orderService.getOne(qw);
        order.setOpenStatus(0);
        order.setDeviceId(deviceId);
        orderService.updateById(order);
        return new CommonResult().success();
    }

    private static List<QsgDevice> collection(List<QsgDevice> devices) {
        for (QsgDevice device : devices) {
            int status = device.getRoom().getStatus();
            if (status == 2) {
                device.setSort(1);
            } else if (status == 1) {
                device.setSort(2);
            } else {
                device.setSort(status);
            }
        }

        Collections.sort(devices, new Comparator<QsgDevice>() {
            public int compare(QsgDevice o1, QsgDevice o2) {
                return o1.getSort() - o2.getSort();
            }
        });
        return devices;
    }

    @ResponseBody
    @RequestMapping(value = "/device/upload", method = RequestMethod.POST)
    public Object upload(MultipartFile file) {
        try {
            String imageUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
            return new CommonResult().success(imageUrl);
        } catch (Exception be) {
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @ApiOperation("保存设备表")
    @PostMapping(value = "/device/create")
    public Object saveDevice(@RequestBody QsgDevice entity) {
        try {
            if (null == entity.getId()) {
                entity.setSort(0);
                entity.setCreateDatetime(new Date());
                deviceService.save(entity);
                QsgRoom room = new QsgRoom();
                room.setStoreId(entity.getStoreId());
                room.setCreateDatetime(new Date());
                room.setDeviceCode(entity.getDeviceCode());
                room.setDeviceId(entity.getId());
                room.setRoomName(entity.getMachineName());
                roomService.save(room);
            } else {
                QsgDevice device = deviceService.getById(entity.getId());
                if (StringUtils.isNotBlank(entity.getMealId())) {
                    String oldId = device.getMealId();
                    String newId = entity.getMealId();
                    if (StringUtils.isNotBlank(oldId)) {
                        String[] res = arrayMerge(oldId,newId);
                        entity.setMealId(StringUtils.join(res,","));
                    }
                }
                if (deviceService.updateById(entity)) {
                    QueryWrapper qw = new QueryWrapper();
                    qw.eq("device_id",entity.getId());
                    QsgRoom room = roomService.getOne(qw);
                    room.setRoomName(entity.getMachineName());
                    room.setDeviceCode(entity.getDeviceCode());
                    roomService.updateById(room);
                    return new CommonResult().success();
                }
            }
            return new CommonResult().success(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    private static QsgDevice setTimeAxis(QsgDevice device) {
        List<Integer> currentTimeArea = device.getCurrentOrderArea();
        List<Integer> yuyueTimeArea = device.getYuyueOrderArea();
        List<TimeAxis> timeAxies = new ArrayList<>();
        String invalidStyle = "background:#6b6b6b;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        String defaultStyle = "background:#E8E8E8;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        String usingStyle = "background:#F04747;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        String yuyueStyle = "background:#0DA944;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        for (int i = 0; i <= 23; i++) {
            TimeAxis timeAxis = new TimeAxis();
            timeAxis.setHour(i);
            if (null != currentTimeArea && currentTimeArea.size() > 0) {
                if (currentTimeArea.contains(i)) {
                    timeAxis.setStyle(usingStyle);
                }
            }
            if (null != yuyueTimeArea && yuyueTimeArea.size() > 0) {
                if (yuyueTimeArea.contains(i)) {
                    timeAxis.setStyle(yuyueStyle);
                }
            }
            if (StringUtils.isBlank(timeAxis.getStyle())) {
                int now = new Date().getHours();
                if (now > i) {
                    timeAxis.setStyle(invalidStyle);
                } else {
                    timeAxis.setStyle(defaultStyle);
                }
            }
            timeAxies.add(timeAxis);
        }
        device.setTimeAxes(timeAxies);
        return device;
    }

    @IgnoreAuth
    @GetMapping(value = "/device/getDeviceGroup")
    @ApiOperation(value = "根据店铺id查询设备列表")
    public Object getDeviceGroup(Long storeId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        List<QsgDevice> devices = deviceService.list(qw);
        if (null != devices && devices.size() > 0) {
            for (QsgDevice device : devices) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("device_id", device.getId());
                QsgRoom room = roomService.getOne(queryWrapper);
                if (device.getOlStatus() == DeviceStatus.OFFLINE.getValue()) {//设备离线时房间离线，并记录下离线前的状态
                    room.setBeforeStatus(room.getStatus());
                    room.setStatus(RoomStatus.OFFLINE.getValue());
                    roomService.updateById(room);
                }
                if (null != room && null != room.getBeforeStatus() && device.getOlStatus() == DeviceStatus.ONLINE.getValue()) {
                    room.setStatus(room.getBeforeStatus());
                    roomService.updateById(room);
                }
                device.setRoom(room);
            }
        }
        return new CommonResult().success(devices);
    }

    @IgnoreAuth
    @GetMapping(value = "/device/getDevicePort")
    @ApiOperation(value = "根据设备代码获取端口")
    public Object getDevicePort(String code) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("device_code", code);
        QsgDevice device = deviceService.getOne(qw);
        if (null != device) {
            return new CommonResult().success(device);
        }
        return new CommonResult().failed();
    }

    @IgnoreAuth
    @GetMapping(value = "/device/getDeviceStatus")
    public Object getDeviceStatus(Long storeId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        int total = deviceService.count(qw);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("ol_status", DeviceStatus.ONLINE.getValue());
        int oldevice = deviceService.count(queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("totalDevice", total);
        result.put("onlineDevice", oldevice);
        result.put("offlineDevice", total - oldevice);
        return new CommonResult().success(result);
    }

    @SysLog(MODULE = "qsg", REMARK = "更新设备表")
    @ApiOperation("更新设备表")
    @PostMapping(value = "/update/{id}")
    public Object updateDevice(@RequestBody QsgDevice entity) {
        try {
            QsgDevice device = deviceService.getById(entity.getId());
            if (StringUtils.isNotBlank(entity.getMealId())) {
                String oldId = device.getMealId();
                String newId = entity.getMealId();
                if (StringUtils.isNotBlank(oldId)) {
                    String[] res = arrayMerge(oldId, newId);
                    entity.setMealId(StringUtils.join(res, ","));
                }
            }
            if (StringUtils.isNotBlank(device.getServerPort())) {
                entity.setServerPort(device.getServerPort());
            }
            if (StringUtils.isNotBlank(device.getServerIp())) {
                entity.setServerIp(device.getServerIp());
            }
            if (deviceService.updateById(entity)) {
                QueryWrapper qw = new QueryWrapper();
                qw.eq("device_id", entity.getId());
                QsgRoom room = roomService.getOne(qw);
                room.setRoomName(entity.getMachineName());
                room.setDeviceCode(entity.getDeviceCode());
                roomService.updateById(room);
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    public static String[] arrayMerge(String a, String b) {
        Set<String> set = new TreeSet<String>();
        for (String s : a.split(","))
            set.add(s);
        for (String s : b.split(","))
            set.add(s);
        return (String[]) set.toArray(new String[0]);
    }

    @IgnoreAuth
    @GetMapping(value = "/getDeviceById")
    @ApiOperation(value = "根据id查询设备")
    public Object getDeviceById(@RequestParam Long id) {
        QsgDevice device = deviceService.getById(id);
        List<String> imgs = new ArrayList<>();
        if (StringUtils.isNotBlank(device.getImageUrl())) {
            imgs.add(device.getImageUrl());
        }
        if (StringUtils.isNotBlank(device.getImageUrl1())) {
            imgs.add(device.getImageUrl1());
        }
        if (StringUtils.isNotBlank(device.getImageUrl2())) {
            imgs.add(device.getImageUrl2());
        }
        device.setImgs(imgs);
        Map<String,Object> params = new HashMap<>();
        params.put("dates",DateUtil.getDateForMeal());
        params.put("device",device);
        return new CommonResult().success(params);
    }

    @IgnoreAuth
    @GetMapping(value = "/device/getDeviceMeal")
    @ApiOperation(value = "根据设备列表查询套餐")
    public Object getDeviceMeal(Long deviceId) {
        try {
            QsgMeal saleMeal = null;
            QsgDevice device = deviceService.getById(deviceId);
            List<QsgMeal> meals = new ArrayList<>();
            String mealId = "";
            if (null != device && StringUtils.isNotBlank(device.getMealId())) {
                String[] ids = StringUtils.split(device.getMealId(), ",");
                for (String id : ids) {
                    QsgMeal meal = mealService.getById(Long.valueOf(id));
                    if (null != meal) {
                        mealId = mealId + id + ",";
                        if (meal.getIsSale() == 0 && meal.getIsXufei() == 0) {
                            meals.add(meal);
                        } else if (meal.getIsSale() == 1 && meal.getIsXufei() == 0) {
                            saleMeal = meal;
                        }
                    }
                }
                if (StringUtils.isNotBlank(mealId)) {
                    mealId = mealId.substring(0, mealId.lastIndexOf(","));
                }
                device.setMealId(mealId);
                deviceService.updateById(device);
            }
            Collections.sort(meals);
            if (null != saleMeal) {
                meals.add(saleMeal);
            }
            return new CommonResult().success(meals);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @GetMapping(value = "/device/getDeviceMealH5")
    @ApiOperation(value = "根据设备列表查询套餐")
    public Object getDeviceMealH5(Long deviceId) {
        try {
            QsgMeal saleMeal = null;
            QsgDevice device = deviceService.getById(deviceId);
            List<QsgMeal> meals = new ArrayList<>();
            String mealId = "";
            if (null != device && StringUtils.isNotBlank(device.getMealId())) {
                String[] ids = StringUtils.split(device.getMealId(), ",");
                for (String id : ids) {
                    QsgMeal meal = mealService.getById(Long.valueOf(id));
                    if (null != meal) {
                        mealId = mealId + id + ",";
                        if (meal.getIsSale() == 0) {
                            meals.add(meal);
                        } else {
                            saleMeal = meal;
                        }
                    }
                }
                if (StringUtils.isNotBlank(mealId)) {
                    mealId = mealId.substring(0, mealId.lastIndexOf(","));
                }
                device.setMealId(mealId);
                deviceService.updateById(device);
            }
            Collections.sort(meals);
            if (null != saleMeal) {
                meals.add(saleMeal);
            }
            return new CommonResult().success(meals);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @ApiOperation("解除套餐绑定")
    @PostMapping(value = "/deleteBind")
    public Object deteleBind(@RequestBody QsgDevice device) {
        try {
            QsgDevice entity = deviceService.getById(device.getId());
            List<String> newMealId = new ArrayList<>();
            String mealIdStr = entity.getMealId();
            String[] arrs = StringUtils.split(mealIdStr, ",");
            for (String arr : arrs) {
                if (!arr.equals(device.getMealId())) {
                    newMealId.add(arr);
                }
            }
            entity.setMealId(StringUtils.join(newMealId, ","));
            deviceService.updateById(entity);
            return new CommonResult().success();
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }
}
